#include "linechartswidget.h"

LineChartsWidget::LineChartsWidget(QWidget *parent)
    : QWidget{parent}
{
    setStyleSheet("background-color: #052753;");


    SetupChart();
    // 添加一个定时器,
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &LineChartsWidget::addNextPoint);
    timer->start(1000);  // 每秒更新一次

}


void LineChartsWidget::SetupChart()
{
    series = new QLineSeries();
    scatterSeries = new QScatterSeries();

    listData << QPointF(0, 0) << QPointF(1, 5) << QPointF(2, 7) << QPointF(3, 7.6)
             << QPointF(4, 7.9) << QPointF(5, 7.8) << QPointF(6, 8.1) << QPointF(7, 8)
             << QPointF(8, 8) << QPointF(9, 8) << QPointF(10, 13) << QPointF(11, 14.8)
             << QPointF(12, 16) << QPointF(13, 17) << QPointF(14, 17.5) << QPointF(15, 17.9)
             << QPointF(16, 18.1) << QPointF(17, 17.9) << QPointF(18, 18) << QPointF(19, 18)
             << QPointF(20, 18);
    // scatterSeries->setMarkerShape(QScatterSeries::MarkerShapeTriangle);
    scatterSeries->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    scatterSeries->setMarkerSize(10);
    scatterSeries->setBrush(Qt::darkGray);

    chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->addSeries(scatterSeries);

    QValueAxis *axisX = new QValueAxis();
    axisX->setRange(0, 20);
    axisX->setMinorTickCount(4);
    axisX->setMinorGridLineVisible(true);
    axisX->setTitleText("时 间");
    axisX->setGridLineColor(Qt::darkGray);
    axisX->setGridLineVisible(true);
    axisX->setLabelFormat("%i");

    QValueAxis *axisY = new QValueAxis();
    axisY->setRange(0, 20);
    axisY->setTickInterval(5);
    axisY->setMinorTickCount(4);
    axisY->setMinorGridLineVisible(true);
    axisY->setTitleText("转 速");
    axisY->setGridLineColor(Qt::darkGray);
    axisY->setGridLineVisible(true);
    axisY->setLabelFormat("%i");

    chart->addAxis(axisX, Qt::AlignBottom);
    chart->addAxis(axisY, Qt::AlignLeft);

    series->attachAxis(axisX);
    series->attachAxis(axisY);
    scatterSeries->attachAxis(axisX);
    scatterSeries->attachAxis(axisY);

    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    // setCentralWidget(chartView);
    QVBoxLayout *layoutLineCharts = new QVBoxLayout(this);
    layoutLineCharts->setContentsMargins(0, 0, 0, 0);  // 设置布局内边距为0，确保按钮紧密排列
    layoutLineCharts->setSpacing(0);
    layoutLineCharts->addWidget(chartView);
}


void LineChartsWidget::addNextPoint()
{
    if (currentIndex < listData.size())
    {
        QPointF point = listData[currentIndex];
        series->append(point);
        scatterSeries->append(point);
        currentIndex++;
    }
    else
    {
        timer->stop();
    }
}
